/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 045. 二叉树最底层最左边的值
 * @author: WXY
 * @create: 2023-01-01 10:48
 * @Version 1.0
 **/
public class offer_fiveteen2_findBottomLeftValue {
    public int findBottomLeftValue(TreeNode root) {
        Info ans = process(root);
        return (int) ans.val;
    }

    private Info process(TreeNode root) {
        if (root == null) {
            return new Info(0, Long.MIN_VALUE);
        }
        Info leftInfo = process(root.left);
        Info rightInfo = process(root.right);
        long val = leftInfo.height >= rightInfo.height ? leftInfo.val : rightInfo.val;
        if (val == Long.MIN_VALUE) val = root.val;
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        return new Info(height, val);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public class Info {
        int height;
        long val;

        public Info(int height, long val) {
            this.height = height;
            this.val = val;
        }
    }
}
